#!/bin/bash

# 管理域同步成功性检测，此脚本需要在tomcat节点执行

# 设置要监控的日志文件路径和关键词
log_file="/app/utcm/apache-tomcat-9.0.44/logs/app/cloud/cloud_error.log"
keyword="Sync resource audit:"

# 告警缓存文件
alarm_file_tmp="sync_check_alarm.txt"

# 系统ID
system_id=$(cat config.cnf | grep SystemId | awk -F "=" '{print $2}')
# 告警存放文件夹
alert_dir=$(cat config.cnf | grep AlertDir | awk -F "=" '{print $2}')
execute_cycle=$(cat config.cnf | grep ExecuteCycle | awk -F "=" '{print $2}')

# 记录当前日志文件的大小和偏移量
log_size=$(wc -c <"${log_file}")
log_pos=$(grep -b -m 1 "" "${log_file}" | awk -F ":" '{print $1}')
# 取缓存数据
log_size=$([[ -f state/oss_sync.txt ]] && cat state/oss_sync.txt | grep LogSize | awk -F "=" '{print $2}' || echo "${log_size}")
log_pos=$([[ -f state/oss_sync.txt ]] && cat state/oss_sync.txt | grep LogPos | awk -F "=" '{print $2}' || echo "${log_pos}")
flag=$([[ -f state/oss_sync.txt ]] && cat state/oss_sync.txt | grep Flag | awk -F "=" '{print $2}' || echo "")

# 本机ip
local_ip=$(ifconfig -a | grep inet | grep -v 127.0.0.1 | grep -v inet6 | awk '{print $2}' | tr -d "addr:")

[[ ! -d alarm ]] && mkdir alarm

# 循环监控
while true; do
    holidays_date=$(cat config.cnf | grep Holidays | awk -F "=" '{print $2}' | sed "s/,/ /g")
	current_date=$(date +'%Y-%m-%d')
	echo $holidays_date | grep -o $current_date >> /dev/null
	if [[ $? -eq 0 ]]; then
		exit 0
	else
		# 清空告警缓存
		echo -n "" >${alarm_file_tmp}
		# 检查日志文件是否被删除或者改名，如果是，重新打开日志文件
		if [[ ! -f "${log_file}" ]]; then
			exec 1>"${log_file}"
			exec 2>&1
			log_size=0
			log_pos=0
		fi

		# 检查日志文件是否被截断，如果是，重新记录日志文件的大小和偏移量
		if [[ "${log_size}" -gt "$(wc -c <"${log_file}")" ]]; then
			log_size=$(wc -c <"${log_file}")
			log_pos=$(($(grep -b -m 1 "${flag}" "${log_file}" | awk -F ":" '{print $1}') + ${#flag}))
		fi

		echo -n "" >state/oss_sync.txt
		# 使用 tail 命令监控日志文件，只输出新增的内容
		[[ -f "${alarm_file_tmp}" ]] && echo -n "" > ${alarm_file_tmp}
		tail -c +${log_pos} "${log_file}" | grep --line-buffered "${keyword}" | while read line; do
			# 发现关键词，告警信息按照规定格式写入文件
			msg=$(echo $line | awk '{print $1" "$2" 管理域[" $13}' | awk -F "-Failed" '{print $1"]同步失败"}')
			alarm=""${system_id}"|+|"$(uuidgen | sed 's/-//g')"|+|"$(date +'%Y%m%d%H%M%S')"|+|日志监控|+|"$msg"|+|2|+||+|"$(hostname -I|awk '{print $1}')"|+|cmp|+|管理域同步|-|"
			echo $alarm >>${alarm_file_tmp}
			echo "Flag=${line} >state/oss_sync.txt"
		done

		# 将告警信息放入制定文件夹
		./gen_alarm.sh -s ${alarm_file_tmp}

		# 更新日志文件的大小和偏移量
		log_size=$(wc -c <"${log_file}")
		log_pos=$log_size

		echo "LogSize=${log_size}" >>state/oss_sync.txt
		echo "LogPos=${log_pos}" >>state/oss_sync.txt

		# 监控采集周期，单位秒
		sleep ${execute_cycle}
		sed -i 's/|2|/|0|/' ${alarm_file_tmp}
		sed -i 's/同步失败/同步失败,现场运维已接手解决/' ${alarm_file_tmp}
		./gen_alarm.sh -s  ${alarm_file_tmp}
		exit 0
	fi
done